#!/bin/bash
# OpenCloudOS 节点管理工具 - 快速启动脚本
# 一键启动完整系统：基础设施 + Server + Agent

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"

echo "🚀 OpenCloudOS节点管理工具 - 快速启动"
echo "====================================="
echo ""

# 1. 启动基础设施
echo "📦 步骤1: 启动基础设施..."
"$SCRIPT_DIR/start.sh"

echo ""
echo "⏳ 等待基础设施完全启动..."
sleep 5

# 2. 编译项目
echo ""
echo "🔨 步骤2: 编译项目..."
cd "$PROJECT_ROOT"
cargo build --release
echo "✅ 编译完成"

# 3. 启动Node Server
echo ""
echo "🖥️  步骤3: 启动Node Server..."
./target/release/node_server start > server.log 2>&1 &
SERVER_PID=$!
echo "✅ Server启动 (PID: $SERVER_PID)"

# 等待Server启动并验证
echo "⏳ 等待Server初始化..."
sleep 5

# 验证Server是否正常启动
if ! ps -p $SERVER_PID > /dev/null; then
    echo "❌ Server启动失败，请检查日志: server.log"
    exit 1
fi

# 4. 启动Node Agent
echo ""
echo "🤖 步骤4: 启动Node Agent..."
./target/release/node_agent --groups web,default --token secure_token_123 > agent.log 2>&1 &
AGENT_PID=$!
echo "✅ Agent启动 (PID: $AGENT_PID)"

# 等待Agent启动并验证
echo "⏳ 等待Agent注册..."
sleep 3

# 验证Agent是否正常启动
if ! ps -p $AGENT_PID > /dev/null; then
    echo "❌ Agent启动失败，请检查日志: agent.log"
    exit 1
fi

echo ""
echo "🎉 系统启动完成！"
echo "================"
echo ""
echo "� 服务状态:"
echo "  🖥️  Server: 运行中 (PID: $SERVER_PID)"
echo "  🤖 Agent:  运行中 (PID: $AGENT_PID)"
echo ""
echo "🔗 访问地址:"
echo "  🐰 RabbitMQ管理界面: http://localhost:15672"
echo "     用户名: admin / 密码: admin123"
echo "  🐘 PostgreSQL: localhost:5432"
echo "     数据库: node_management / 用户: admin / 密码: admin123"
echo ""
echo "� 日志文件:"
echo "  Server: server.log"
echo "  Agent:  agent.log"
echo ""
echo "🧪 快速测试:"
echo "  # 获取节点主机名"
echo "  ./target/release/node_server command get-hostname"
echo ""
echo "  # 执行简单脚本"
echo "  ./target/release/node_server command run-script \\"
echo "    --script 'echo \"Hello from \$(hostname)\"' --timeout 10"
echo ""
echo "  # 向特定分组发送命令"
echo "  ./target/release/node_server command --group web get-hostname"
echo ""
echo "🛑 停止系统:"
echo "  ./deploy/scripts/stop.sh"
echo ""
echo "📚 更多测试:"
echo "  ./tests/quick_test.sh      # 快速功能测试"
echo "  ./tests/functional_test.sh # 完整功能测试"
